import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class RemoteIOCopyServer extends Thread {
	private final int port;
	private final String dest;

	public RemoteIOCopyServer(int port, String dest) {
		this.port = port;
		this.dest = dest;
	}

	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Invalid parameters list. Usage: RemoteIOCopyServer <port> <dest file> ");
			System.exit(1);
		}
		int port = Integer.parseInt(args[0]);
		String dest = args[1];
		RemoteIOCopyServer server = new RemoteIOCopyServer(port, dest);
		server.start();
	}

	public void run() {
		try (ServerSocket serverSocket = new ServerSocket(port);
				Socket socket = serverSocket.accept();
				BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(dest))) {
			DataInputStream in = new DataInputStream(socket.getInputStream());
			OutputStream out = socket.getOutputStream();
			out.flush();
			byte[] buffer = new byte[100000];
			int fileSize = in.readInt();
			int size = 0;
			int sum = 0;
			while ((size = in.read(buffer)) != -1) {
				fileOut.write(buffer, 0, size);
				if ((sum += size) >= fileSize) {
					break;
				}
			}
			out.write(1);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
